<template>
    <div class="image-uploader">
      <div class="image-list">
        <template v-if="images.length > 0">
          <div
            v-for="(image, index) in images"
            :key="image.id"
            class="image-item"
          >
            <el-image
              :src="image.imgUrl"
              fit="cover"
              :preview-src-list="[image.imgUrl]"
              hide-on-click-modal
            />
            <div class="image-label">{{ image.imgName || label }}</div>
            <div class="delete-btn" @click="handleDelete(index)">
              <el-icon><Delete /></el-icon>
            </div>
          </div>
        </template>
        <div class="upload-item" v-if="images.length < 9">
          <el-upload
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="yuanhandleGoodImgUpload"
            multiple
          >
            <el-icon class="upload-icon"><Plus /></el-icon>
          </el-upload>
        </div>
      </div>
    </div>
  </template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";
import type { UploadUserFile as UploadFile } from "element-plus";
import { Delete, Plus } from "@element-plus/icons-vue";
import axios from "axios";
import { ElMessage } from "element-plus";

interface ImageInfo {
  id: number;
  imgName: string;
  imgUrl: string;
  imgType: number;
  batch: string;
}

const props = defineProps<{
  type: number;
  label: string;
  productionBatch: string;
}>();

const images = ref<ImageInfo[]>([]);

// 获取图片列表
const fetchImages = async () => {
  try {
    console.log("获取图片列表参数:", {
      batch: props.productionBatch,
      type: props.type,
    });

    const response = await axios.get(
      "http://localhost:5045/api/Img/GetImageShow",
      {
        params: {
            batch: props.productionBatch,
            imgType: props.type,
        },
      }
    );

    console.log("获取图片列表响应:", response.data);

    if (response.data && response.data.code == 200) {
      const data = response.data.data || [];
      images.value = Array.isArray(data)
        ? data.filter((item: any) => {
            const isValid =
              item && item.imgUrl && item.imgType == props.type;

            console.log("图片项检查:", {
              item,
              isValid,
              expectedType: props.type,
            });

            return isValid;
          })
        : [];

      console.log("筛选后的图片列表:", images.value);
    }
  } catch (error) {
    console.error(`获取类型 ${props.type} 的图片列表失败:`, error);
    ElMessage.error("获取图片列表失败");
  }
};
function yuanhandleGoodImgUpload(file: any) {
  const formData = new FormData();
  formData.append("formFiles", file.raw);
  formData.append("imgType", props.type.toString());
  formData.append("batch", props.productionBatch);

  console.log("开始上传文件:", {
    fileName: file.raw.name,
    batch: props.productionBatch,
    type: props.type,
  });

  // 第一步：上传文件到MinIO
  axios
    .post("http://localhost:5045/api/MinioImg/UploadFiles", formData)
    .then((res) => {
      console.log("MinIO上传响应:", res.data);

      // 检查返回的数据是否是数组
      if (res.data && Array.isArray(res.data)) {
        const imgUrls = res.data.filter(
          (url: string) => typeof url === "string" && url.startsWith("http")
        );

        if (imgUrls.length === 0) {
          console.error("MinIO上传成功但未返回有效URL");
          ElMessage.error("未获取到有效的图片URL");
          return;
        }

        console.log("获取到的图片URL:", imgUrls);

        // 第二步：创建图片记录
        const createPromises = imgUrls.map((imgUrl: string) => {
          const imgInfo = {
            imgName: props.label, // 使用文件原始名称，如果没有则使用标签名
            imgUrl: imgUrl,
            imgType: props.type,
            batch: props.productionBatch,
          };

          console.log("创建图片记录:", imgInfo);

          return axios.post(
            "http://localhost:5045/api/Img/AddImg",
            imgInfo
          );
        });

        return Promise.all(createPromises);
      } else {
        throw new Error("上传返回格式不正确");
      }
    })
    .then((createResults) => {
      if (Array.isArray(createResults) && createResults.length > 0) {
        console.log(
          "所有图片记录创建响应:",
          createResults.map((res) => res.data)
        );

        const allSuccess = createResults.every(
          (res) => res.data && res.data.code == 200
        );
        if (allSuccess) {
          ElMessage.success("上传成功");
          fetchImages(); // 刷新图片列表
        } else {
          const failedCount = createResults.filter(
            (res) => !res.data || res.data.code != 200
          ).length;
          ElMessage.warning(
            `部分图片上传失败 (${failedCount}/${createResults.length})`
          );
          fetchImages(); // 即使部分失败也刷新列表
        }
      }
    })
    .catch((error) => {
      console.error("上传过程出错:", error);
      ElMessage.error(error.response?.data?.msg || error.message || "上传失败");
    });
}

// 处理图片删除
const handleDelete = async (index: number) => {
  try {
    const image = images.value[index];
    if (!image) return;

    const response = await axios({
      url: "http://localhost:5045/api/Img/DelImg",
      method: "delete",
      data: {
        id: image.id,
        batch: image.batch,
        imgType: image.imgType,
      },
    });

    if (response.data.code === 200) {
      images.value.splice(index, 1);
      ElMessage.success("删除成功");
    } else {
      ElMessage.error(response.data.msg || "删除失败");
    }
  } catch (error) {
    console.error("删除失败:", error);
    ElMessage.error("删除失败，请检查网络连接");
  }
};

onMounted(async () => {
  await fetchImages();
});
</script>













  <style scoped>
  .image-uploader {
    width: 100%;
    padding: 16px;
  }
  
  .image-list {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
  }
  
  .image-item {
    width: 160px;
    height: 200px;  /* 增加高度以容纳标签 */
    position: relative;
    border-radius: 4px;
    overflow: hidden;
    border: 1px solid #ebeef5;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  }

  .image-item .el-image {
    width: 100%;
    height: 160px;
    display: block;
  }

  .image-label {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 40px;
    background-color: #fff;
    padding: 8px;
    text-align: center;
    font-size: 12px;
    color: #606266;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .delete-btn {
    position: absolute;
    top: 8px;
    right: 8px;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    background-color: rgba(0,0,0,0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    color: #fff;
    transition: all 0.3s;
  }

  .delete-btn:hover {
    background-color: rgba(0,0,0,0.7);
  }

  .upload-item {
    width: 160px;
    height: 160px;
    border: 1px dashed #d9d9d9;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s;
  }

  .upload-item:hover {
    border-color: #409EFF;
  }

  .upload-icon {
    font-size: 28px;
    color: #8c939d;
  }

  .upload-item:hover .upload-icon {
    color: #409EFF;
  }
  </style>